package com.xinyu.notification;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class MailTemplateRenderer {

    private static final Logger log = LoggerFactory.getLogger(MailTemplateRenderer.class);
    private final Map<String, String> templateCache = new ConcurrentHashMap<>();

    public String render(String templateName, Map<String, Object> variables) {
        String template = templateCache.computeIfAbsent(templateName, this::loadTemplate);
        if (template == null) {
            return null;
        }
        String rendered = template;
        if (variables != null) {
            for (Map.Entry<String, Object> entry : variables.entrySet()) {
                String placeholder = "{{" + entry.getKey() + "}}";
                rendered = StringUtils.replace(rendered, placeholder,
                        entry.getValue() == null ? "" : entry.getValue().toString());
            }
        }
        return rendered;
    }

    private String loadTemplate(String templateName) {
        ClassPathResource resource = new ClassPathResource("templates/" + templateName);
        if (!resource.exists()) {
            log.warn("邮件模板 {} 不存在", templateName);
            return null;
        }
        try (InputStream is = resource.getInputStream()) {
            return StreamUtils.copyToString(is, StandardCharsets.UTF_8);
        } catch (IOException e) {
            log.warn("读取邮件模板 {} 失败: {}", templateName, e.getMessage());
            return null;
        }
    }
}
